<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--card卡片-->
    <el-card>
      <!--警告-->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!--步骤条-->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--tabs标签页-->
      <el-form :model="goodsForm" :rules="goodsRules" ref="goodsRef"
               label-position="top" class="demo-ruleForm">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeLeaveTabs" @tab-click="tabChange">
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodsForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="item in attrList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item2" v-for="(item2, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in propertyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              :headers="headerObj"
              :action="uploadURL"
              :on-preview="filePreview"
              :on-remove="fileRemove"
              :on-success="fileSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor
              ref="myQuillEditor"
              v-model="goodsForm.goods_introduce"/>
            <el-button type="primary" @click="addGoods" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!---->
    <!---->
    <!---->
    <!--预览图片-->
    <el-dialog
      title="预览图片"
      :visible.sync="previeDialog"
      width="50%">
      <img :src="previewUrl" alt="预览图片">
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    data() {
      return {
        // 步骤条
        activeIndex: '0',
        // tabs标签页，form表单
        goodsForm: {
          goods_name: '',
          goods_cat: [],
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          goods_introduce: '',
          pics: []
        },
        // 级联选择器的值
        cateList: [],
        props: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // form表单验证规则
        goodsRules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' }
          ],
          goods_cat: [
            { required: true, message: '请选择商品分类', trigger: 'blur' }
          ]
        },
        // 商品参数列表
        attrList: [],
        // 商品属性列表
        propertyList: [],
        // 上传图片
        uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        previewUrl: '',
        previeDialog: false
      }
    },
    computed: {
      cateId: function () {
        if (this.goodsForm.goods_cat.length === 3) {
          return this.goodsForm.goods_cat[2]
        }
        return null
      }
    },
    created () {
      this.getCateList()
    },
    methods: {
      // 商品分类数据列表
      getCateList: async function() {
        const { data: res } = await this.$http.get('categories')
        if (res.meta.status !== 200) return this.$message.error('获取商品分类数据列表失败！')
        this.cateList = res.data
      },
      // 级联选择器，选择的值
      handleChange: function (value) {
        if (value.length !== 3) {
          this.goodsForm.goods_cat = []
        }
      },
      // 验证form表单是否符合规则
      valid: function () {
        let boo = null
        this.$refs.goodsRef.validate(valid => {
          boo = valid
        })
        return boo
      },
      // 切换tab标签之前的钩子
      beforeLeaveTabs: function (activeName, oldActiveName) {
        const boo = this.valid()
        if (this.goodsForm.goods_cat.length !== 3) {
          this.$message.error('请选择商品分类')
          return false
        }
        if (oldActiveName === '0' && !boo) {
          this.$message.error('请填写完整基本信息')
          return false
        }
      },
      // 获取商品参数、商品属性
      getAttr: async function () {
        if (this.activeIndex === '1') {
          const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
            params: { sel: 'many' }
          })
          if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          })
          this.attrList = res.data
        } else {
          const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
            params: { sel: 'only' }
          })
          if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
          this.propertyList = res.data
        }
      },
      // 切换tab标签
      tabChange: function (tab) {
        if (tab.index === '1' || tab.index === '2') {
          this.getAttr()
        }
      },
      // 删除上传的图片
      fileRemove: function(file) {
        this.goodsForm.pics.splice(this.goodsForm.pics.indexOf(file.response.data.tmp_path), 1)
      },
      // 预览上传的图片
      filePreview(file) {
        this.previewUrl = file.response.data.url
        this.previeDialog = true
      },
      // 图片上传成功
      fileSuccess: function (response) {
        this.goodsForm.pics.push(
          { pic: response.data.tmp_path }
        )
      },
      addGoods: function () {
        this.$refs.goodsRef.validate(async valid => {
          if (!valid) return this.$message.error('请填写必要的表单项！')
          var form = _.cloneDeep(this.goodsForm)
          form.goods_cat = form.goods_cat.join(',')
          form.attrs = []
          this.attrList.forEach(item => {
            const attrInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(',')
            }
            form.attrs.push(attrInfo)
          })
          this.propertyList.forEach(item => {
            const propertyInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            form.attrs.push(propertyInfo)
          })
          const { data: res } = await this.$http.post('goods', form)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('创建商品成功！')
          this.$router.push('/goods')
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-steps{
    margin: 30px 50px;
  }
  .el-step__title{
    font-size: 12px;
  }
  .el-checkbox{
    margin: 0 10px 0 0!important;
  }
  img{
    width: 100%;
  }
  .addBtn{
    margin-top: 15px;
  }
</style>
